package com.devstringx.pmt.service.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.devstringx.pmt.domain.common.RoleDetailsDTO;
import com.devstringx.pmt.domain.common.UserDetailsDTO;
import com.devstringx.pmt.form.common.UserRegistrationForm;
import com.devstringx.pmt.mail.PmtEmailService;
import com.devstringx.pmt.persitence.common.CommonApplicationDAO;

@Service
@Transactional(propagation=Propagation.REQUIRED)
public class CommonService {

	Logger  logger=Logger.getLogger(getClass());
	@Autowired
	PmtEmailService emailService;

	@Autowired
	CommonApplicationDAO commonApplicationDAO;

	public void registerNewUser(UserRegistrationForm userRegistrationForm){

		System.out.println("registering..");

		UserDetailsDTO userDetailsDTO=new UserDetailsDTO();
        		 
		userDetailsDTO.setEmailId(userRegistrationForm.getEmailId());
		userDetailsDTO.setUsername(userRegistrationForm.getUserId());
		userDetailsDTO.setPassword(userRegistrationForm.getPassword());
        userDetailsDTO.setCreatedDate(new Date(System.currentTimeMillis()));
        userDetailsDTO.setUserDisplayNameFirst("Rajeev");
        userDetailsDTO.setStrCreatedAuthor("System");
        RoleDetailsDTO roleDetailsDTO=new RoleDetailsDTO("USER", "ROLE_USER");
        ArrayList<GrantedAuthority> roleDetailsDTOs=new ArrayList<GrantedAuthority>();
        roleDetailsDTOs.add(roleDetailsDTO);
        userDetailsDTO.setAuthorities(roleDetailsDTOs);
        commonApplicationDAO.insertNewRow(userDetailsDTO);
        emailService.sendRegistrationEmail(userDetailsDTO.getEmailId(), userRegistrationForm.getUserId());
		logger.debug("User registration mail send successfully !!");
	}



}
